//
//  ViewController.m
//  LZHApplePayTest
//
//  Created by 刘志恒 on 16/11/1.
//  Copyright © 2016年 Jack. All rights reserved.
//

#import "ViewController.h"
#import <PassKit/PassKit.h>
#import "LZHConst.h"
#import "UPPaymentControl.h"
@interface ViewController ()<PKPaymentAuthorizationViewControllerDelegate,UPAPayPluginDelegate,UIAlertViewDelegate,NSURLConnectionDelegate,NSURLConnectionDataDelegate>


{
    NSMutableData *_responseData;
}
//流水单号类型
@property(nonatomic,strong)NSString *tnMode;
//是否是集成的ApplePay标准控件开发包
@property(nonatomic,assign)BOOL isStandard;

@end

@implementation ViewController


#pragma mark 测试------正式使用时,选择正式环境 "00"
- (IBAction)UPBtn:(id)sender {
    
    _isStandard=NO;
    _tnMode=testMode;
    [self startNetWithURL:[NSURL URLWithString:tnURLNormal]];
    
}

- (IBAction)Real:(id)sender {
    
//    if ([[UPPaymentControl defaultControl] isPaymentAppInstalled])
//    {
//正式使用时,上边注释内容判断是否手机已安装银联支付
    _tnMode=testMode;
    _isStandard=YES;
    [self startNetWithURL:[NSURL URLWithString:tnURLNormal]];
//}
}


#pragma mark Step1.发送请求
- (void)startNetWithURL:(NSURL *)url
{
    [self showAlertWithTitle:waiting];
    NSURLRequest * urlRequest=[NSURLRequest requestWithURL:url];
    NSURLConnection* urlConn = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
    [urlConn start];
}

#pragma mark Step2.开始接收到回调
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSHTTPURLResponse* rsp = (NSHTTPURLResponse*)response;
    NSInteger code = [rsp statusCode];
    if (code != 200)
    {
        [self showAlertWithTitle:errorNet];
        [connection cancel];
    }
    else
    {
        _responseData = [[NSMutableData alloc] init];
    }
    
}

#pragma mark Step3.回调数据接收完成
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [_responseData appendData:data];
    
}

#pragma mark Step4.加载完成
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    //根据返回的二进制数据生成流水单号
    NSString* tn = [[NSMutableString alloc] initWithData:_responseData encoding:NSUTF8StringEncoding];
    //当账单号符合要求时----开始申请付款
    if (tn != nil && tn.length > 0)
    {
        if (_isStandard)//标准控件开发包
        {
            NSLog(@"tn=%@",tn);
            [[UPPaymentControl defaultControl] startPay:tn fromScheme:URLScheme mode:_tnMode viewController:self];
        }else
        {
            //判断是否支持Apple Pay功能,以及是否已加载有可用的支付卡片。
            if([PKPaymentAuthorizationViewController canMakePaymentsUsingNetworks:@[PKPaymentNetworkChinaUnionPay]])
            {
                //此处也可手动填写订单号
                [UPAPayPlugin startPay:tn mode:self.tnMode viewController:self delegate:self andAPMechantID:appleMerchatID];
            }
        }
    }
}

#pragma mark Step5.可能会请求错误 显示错误信息
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    [self showAlertWithTitle:errorNet];
}
#pragma mark Step6.回调付款结果
-(void)UPAPayPluginResult:(UPPayResult *)payResult
{
    if (_isStandard)
    {
        NSString *backResult=[NSString stringWithFormat:WKCResult,payResult];
        [self showAlertWithTitle:backResult];
    }else
    {
        if(payResult.paymentResultStatus == UPPaymentResultStatusSuccess)//支付成功
        {
            NSString *otherInfo = payResult.otherInfo?payResult.otherInfo:@"";
            NSString *successInfo = [NSString stringWithFormat:@"支付成功\n%@",otherInfo];
            [self showAlertWithTitle:successInfo];
        }else if(payResult.paymentResultStatus == UPPaymentResultStatusCancel)//取消支付
        {
            [self showAlertWithTitle:@"支付取消"];
        }else if (payResult.paymentResultStatus == UPPaymentResultStatusFailure)//支付失败
        {
            NSString *errorInfo = [NSString stringWithFormat:@"%@",payResult.errorDescription];
            [self showAlertWithTitle:errorInfo];
        }else if (payResult.paymentResultStatus == UPPaymentResultStatusUnknownCancel)
        {
            //TODO UPPAymentResultStatusUnknowCancel表示发起支付以后用户取消，导致支付状态不确认，需要查询商户后台确认真实的支付结果
            NSString *errorInfo = [NSString stringWithFormat:@"支付过程中用户取消了，请查询后台确认订单"];
            [self showAlertWithTitle:errorInfo];
            
        }
    }
    
}


#pragma mark 提示框
//Alert
-(void)showAlertWithTitle:(NSString *)title
{
    MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.label.text=title;
    [hud hideAnimated:YES afterDelay:2];
}
-(void)showAlertErrorWithTitle:(NSString *)title
{
    [SVProgressHUD showErrorWithStatus:title];
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [SVProgressHUD dismiss];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
}

#pragma mark 情况1:首先判断设备是否可用来pay 检测设备是否可以支持App Pay支付  检测设备是否可以添加银行卡
#pragma mark  情况2:你的设备支持 但是没有添加银行卡  需要添加银行卡
- (IBAction)ApplePay:(id)sender {
    
    //先判断设备是否可用
    if (![PKPaymentAuthorizationViewController canMakePayments]) {
        //不可用 支付按钮不能显示
        return;
        
    }
    
    if (![PKPaymentAuthorizationViewController canMakePaymentsUsingNetworks:@[PKPaymentNetworkChinaUnionPay,PKPaymentNetworkVisa]]){
#pragma mark 当不支持银联和visa银行卡时
        //进入设置银行卡的界面  跳转到设置银行卡的界面
        [[[PKPassLibrary alloc]init] openPaymentSetup];;
        
        
        return;
    }
    //创建请求
    PKPaymentRequest *request = [[PKPaymentRequest alloc]init];
    
    //设置商户的ID
    request.merchantIdentifier = @"merchant.JACK.LZHApplePayTest";
    
    //设置国家的code
    request.countryCode = @"CN";
    
    //设置支持银行卡的类型
    request.supportedNetworks = @[PKPaymentNetworkChinaUnionPay,PKPaymentNetworkVisa];
    
    //设置商户的支付标准
    request.merchantCapabilities = PKMerchantCapability3DS;
    
    //设置货币单位
    request.currencyCode = @"CNY";
    
    //设置商品
    NSDecimalNumber *num1 = [NSDecimalNumber decimalNumberWithString:@"26"];
    
    PKPaymentSummaryItem *item1 = [PKPaymentSummaryItem summaryItemWithLabel:@"杜蕾斯" amount:num1];
    
    NSDecimalNumber *num2 = [NSDecimalNumber decimalNumberWithString:@"30"];
    
    PKPaymentSummaryItem *item2 = [PKPaymentSummaryItem summaryItemWithLabel:@"冈本" amount:num2];
    
    NSDecimalNumber *num3 = [NSDecimalNumber decimalNumberWithString:@"56"];
    
    PKPaymentSummaryItem *item3 = [PKPaymentSummaryItem summaryItemWithLabel:@"总价" amount:num3];
    
    request.paymentSummaryItems = @[item1,item2,item3];
    
    //设置发票收据的必填内容
    request.requiredBillingAddressFields = PKAddressFieldAll;
    
    //设置收件地址
    request.requiredShippingAddressFields = PKAddressFieldAll;
    
    //设置送货方式
    NSDecimalNumber *num4 = [NSDecimalNumber decimalNumberWithString:@"25"];
    
    PKShippingMethod *method = [PKShippingMethod summaryItemWithLabel:@"顺丰" amount:num4];
    method.identifier = @"sf";
    
    method.detail = @"24小时之内发货";
    
    NSDecimalNumber *num5 = [NSDecimalNumber decimalNumberWithString:@"25"];
    
    PKShippingMethod *method1 = [PKShippingMethod summaryItemWithLabel:@"圆通" amount:num5];
    method1.identifier = @"yt";
    
    method1.detail = @"4小时之内发货";
    
    NSDecimalNumber *num6 = [NSDecimalNumber decimalNumberWithString:@"25"];
    
    PKShippingMethod *method2 = [PKShippingMethod summaryItemWithLabel:@"韵达" amount:num6];
    method2.identifier = @"yd";
    
    method2.detail = @"12小时之内发货";
    
    request.shippingMethods = @[method,method1,method2];
    //显示支付界面
    PKPaymentAuthorizationViewController *pay = [[PKPaymentAuthorizationViewController alloc]initWithPaymentRequest:request];
    
    pay.delegate = self;
    
    [self presentViewController:pay animated:YES completion:nil];
}


    
    
    
#pragma mark 点击“使用密码支付”进行的方法
- (void)paymentAuthorizationViewController:(PKPaymentAuthorizationViewController *)controller
                       didAuthorizePayment:(PKPayment *)payment
                                completion:(void (^)(PKPaymentAuthorizationStatus status))completion{
    
    //点击了密码支付 将支付信息发送给服务器 根据服务器返回的处理信息 成功于否 进行不同的结果显示
    
    
    //然后传给不同的枚举值
    completion(PKPaymentAuthorizationStatusSuccess);
}


- (void)paymentAuthorizationViewControllerDidFinish:(PKPaymentAuthorizationViewController *)controller{
    
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

    
    
    
    
    
    
    
    
    
@end
